using Services;
using UnityEngine;

[RequireComponent(typeof(PointTrigger_Player))]
public class Shop : MonoBehaviour
{
    private PointTrigger_Player trigger;
    private CommodityContainer container;
    private GameManager gameManager;
    private GlobalGameCycle gameCycle;
    private EventSystem eventSystem;

    private bool b_justClosed;

    private void Awake()
    {
        container = GetComponentInChildren<CommodityContainer>();
        gameCycle = ServiceLocator.Get<GlobalGameCycle>();
        eventSystem = ServiceLocator.Get<EventSystem>();
        trigger = GetComponent<PointTrigger_Player>();
        trigger.OnTriggerStay += MyOnTriggerStay;
    }

    private void OnEnable()
    {
        eventSystem.AddListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void OnDisable()
    {
        eventSystem.RemoveListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void Start()
    {
        gameManager = ServiceLocator.Get<GameManager>();
    }

    private void MyOnTriggerStay(Player player)
    {
        if (gameManager.GameState == EGameState.Default && Input.GetKeyDown(KeyCode.F) && !b_justClosed)
        {
            player.LeftContainer = container;
            gameManager.GameState = EGameState.Purchase;
        }
    }

    private void OnGameStateChange(EGameState from, EGameState to)
    {
        if (to == EGameState.Default && from == EGameState.Purchase)
        {
            b_justClosed = true;
            gameCycle.AttachToGameCycle(EInvokeMode.NextUpdate, DelayOpen);
        }
    }

    private void DelayOpen()
    {
        b_justClosed = false;
    }
}